<template>
  <div class="layout-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-left">
        <div class="logo">
          <img src="/static/png/iconfont/logo.png" alt="Logo" class="logo-img" />
        </div>
      </div>
      <div class="header-right">
        <!-- 我的消息 -->
        <div class="message-icon" @click="showMessages">
          <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="message-badge">
            <el-icon class="message-bell"><Bell /></el-icon>
          </el-badge>
        </div>
        <span class="username" v-if="userInfoStore.userInfo && userInfoStore.userInfo.user">{{ userInfoStore.userInfo.user.userId }}</span>
        <el-dropdown trigger="click">
          <div class="user-avatar">
            <img src="/src/assets/avatar.jpg" alt="Avatar" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="goToProfile">个人信息</el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 主体内容区域 -->
    <div class="main-container">
      <!-- 侧边栏 -->
      <div class="sidebar" :class="{ 'sidebar-collapsed': isCollapsed }">
        <!-- 收起菜单按钮 -->
        <div class="collapse-btn" @click="toggleCollapse">
          <el-icon v-if="isCollapsed"><Expand /></el-icon>
          <el-icon v-else><Fold /></el-icon>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical"
          :collapse="isCollapsed"
          router
          background-color="#fff"
          text-color="#8d6748"
          active-text-color="#6e4f32"
        >
          <!-- 常规菜单项 -->
          <template v-for="item in menuList" :key="item.path">
            <!-- 有子菜单的情况 -->
            <el-sub-menu v-if="item.children && item.children.length > 0" :index="item.path">
              <template #title>
                <div class="menu-icon-wrapper">
                  <img v-if="item.customIcon" :src="item.customIcon" class="menu-custom-icon" />
                  <el-icon v-else><component :is="item.icon" /></el-icon>
                </div>
                <span>{{ item.label }}</span>
              </template>
              <el-menu-item v-for="child in item.children" :key="child.path" :index="child.path">
                <div class="menu-icon-wrapper">
                  <img v-if="child.customIcon" :src="child.customIcon" class="menu-custom-icon" />
                  <el-icon v-else><component :is="child.icon" /></el-icon>
                </div>
                <span>{{ child.label }}</span>
              </el-menu-item>
            </el-sub-menu>
            
            <!-- 没有子菜单的情况 -->
            <el-menu-item v-else :index="item.path">
              <div class="menu-icon-wrapper">
                <img v-if="item.customIcon" :src="item.customIcon" class="menu-custom-icon" />
                <el-icon v-else><component :is="item.icon" /></el-icon>
              </div>
              <span>{{ item.label }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </div>

      <!-- 内容区域 -->
      <div class="content">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-container" v-if="breadcrumbs.length > 0">
          <el-breadcrumb separator="/" class="global-breadcrumb">
            <el-breadcrumb-item v-for="item in breadcrumbs" :key="item.path" :to="{ path: item.path }">
              {{ item.label }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <!-- 路由视图 -->
        <div class="router-view-container">
          <router-view />
        </div>
      </div>
    </div>

    <!-- 消息抽屉 -->
    <el-drawer
      v-model="messageDrawerVisible"
      title="我的消息"
      direction="rtl"
      size="30%"
    >
      <div class="message-drawer-content">
        <div v-if="messages.length === 0 && !loading" class="no-messages">
          暂无消息
        </div>
        <div v-else-if="loading" class="loading-messages">
          加载中...
        </div>
        <div v-else class="message-list">
          <div 
            v-for="(message, index) in messages" 
            :key="index" 
            class="message-item"
            :class="{ 'unread': !message.isRead }"
            @click="readMessage(message)"
          >
            <div class="message-header">
              <span class="message-title">{{ message.title }}</span>
              <span class="message-time">{{ formatTime(message.time) }}</span>
            </div>
            <div class="message-content">{{ message.content }}</div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { computed, ref, watch, onMounted, onBeforeUnmount } from 'vue'
import { useUserInfoStore } from '@/stores/userInfo'
import { logout, getUserMessages, getUnreadMessageCount, markMessageAsRead } from '@/api/user'
import { ElMessage } from 'element-plus'
import { 
  ArrowDown, House, Suitcase, Document, ChatLineRound, 
  User, List, SetUp, Location, InfoFilled, Fold, Expand, Bell
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const userInfoStore = useUserInfoStore()
const activeMenu = computed(() => route.path)
const isCollapsed = ref(false)

// 消息相关
const messageDrawerVisible = ref(false)
const unreadCount = ref(0)
const messages = ref([])
const loading = ref(false)

// 显示消息抽屉
const showMessages = () => {
  messageDrawerVisible.value = true
  fetchMessages()
}

// 获取消息列表
const fetchMessages = async () => {
  loading.value = true
  try {
    const userId = userInfoStore.userInfo?.user?.userId
    if (!userId) {
      console.warn('用户未登录，无法获取消息')
      return
    }
    
    const res = await getUserMessages(userId)
    console.log('获取消息响应:', res)
    
    // 处理响应数据
    if (res.data && res.data.code === 200) {
      // 标准响应格式
      if (Array.isArray(res.data.data)) {
        messages.value = res.data.data
      } else if (res.data.data && Array.isArray(res.data.data.records)) {
        messages.value = res.data.data.records
      } else {
        // 无消息也是正常情况
        messages.value = []
      }
    } else if (Array.isArray(res.data)) {
      // 直接返回数组的情况
      messages.value = res.data
    } else {
      // API返回其他格式，将其视为空消息列表
      messages.value = []
    }
  } catch (error) {
    // 捕获错误但不显示错误消息，视为空消息列表
    console.log('获取消息时遇到异常，视为无消息')
    messages.value = []
  } finally {
    loading.value = false
  }
}

// 阅读消息
const readMessage = async (message) => {
  if (!message.isRead) {
    try {
      await markMessageAsRead(message.id)
     message.isRead = true
      updateUnreadCount()
    
    // 根据消息类型跳转到相应页面
      navigateToMessageDetail(message)
    } catch (error) {
      console.error('标记消息已读错误:', error)
    }
  } else {
    navigateToMessageDetail(message)
  }
  
  messageDrawerVisible.value = false
}

// 根据消息类型导航到详情页面
const navigateToMessageDetail = (message) => {
  // 根据消息类型跳转到不同页面
  switch (message.type) {
    case 'review_reply':
      router.push(`/review?id=${message.relatedId}`)
      break
    case 'order_update':
      router.push(`/order?id=${message.relatedId}`)
      break
    case 'hotel_review':
      // 酒店商家查看评论
      router.push(`/my-hotel/reviews?id=${message.relatedId}`)
      break
    default:
      router.push('/messages')
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  
  const now = new Date()
  const messageDate = new Date(time)
  const diffMs = now.getTime() - messageDate.getTime()
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    // 今天
    return `今天 ${messageDate.getHours().toString().padStart(2, '0')}:${messageDate.getMinutes().toString().padStart(2, '0')}`
  } else if (diffDays === 1) {
    // 昨天
    return `昨天 ${messageDate.getHours().toString().padStart(2, '0')}:${messageDate.getMinutes().toString().padStart(2, '0')}`
  } else {
    // 更早
    return `${messageDate.getFullYear()}-${(messageDate.getMonth() + 1).toString().padStart(2, '0')}-${messageDate.getDate().toString().padStart(2, '0')} ${messageDate.getHours().toString().padStart(2, '0')}:${messageDate.getMinutes().toString().padStart(2, '0')}`
  }
}

// 获取未读消息数量
const updateUnreadCount = async () => {
  try {
    const userId = userInfoStore.userInfo?.user?.userId
    if (!userId) {
      console.warn('用户未登录，无法获取未读消息数量')
      unreadCount.value = 0
      return
    }
    
    const res = await getUnreadMessageCount(userId)
    console.log('获取未读消息数量响应:', res)
    
    if (res.data && typeof res.data.data === 'number') {
      unreadCount.value = res.data.data
    } else if (typeof res.data === 'number') {
      unreadCount.value = res.data
    } else {
      // 如果后端API未实现，则计算本地消息中的未读数量
      unreadCount.value = messages.value.filter(msg => !msg.isRead).length
    }
  } catch (error) {
    // 捕获错误但不显示错误消息
    console.log('获取未读消息数量时遇到异常，视为无未读消息')
    unreadCount.value = messages.value.filter(msg => !msg.isRead).length
  }
}

// 切换侧边栏折叠状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 面包屑导航数据
const breadcrumbs = ref([])

// 更新面包屑导航函数
const updateBreadcrumbs = (path) => {
  const crumbs = []
  
  // 首页始终是第一个
  crumbs.push({ path: '/home', label: '首页' })
  
  // 根据当前路径构建面包屑
  if (path.startsWith('/my-hotel')) {
    crumbs.push({ path: '/my-hotel', label: '我的酒店' })
    
    if (path === '/my-hotel/detail') {
      crumbs.push({ path: '/my-hotel/detail', label: '酒店详情' })
    } else if (path === '/my-hotel/rooms') {
      crumbs.push({ path: '/my-hotel/rooms', label: '房间管理' })
    } else if (path === '/my-hotel/orders') {
      crumbs.push({ path: '/my-hotel/orders', label: '订单管理' })
    } else if (path === '/my-hotel/reviews') {
      crumbs.push({ path: '/my-hotel/reviews', label: '评价管理' })
    }
  } else if (path.startsWith('/hotel')) {
    // 处理酒店列表及其子页面
    crumbs.push({ path: '/booking', label: '我要订房' })
    crumbs.push({ path: '/hotel', label: '酒店列表' })
    
    // 检查是否是酒店详情页面
    if (path.includes('/detail')) {
      const hotelName = route.params.hotelName
      crumbs.push({ path: `/hotel/${hotelName}/detail`, label: '酒店详情' })
    } 
    // 检查是否是酒店房间页面
    else if (path.includes('/rooms')) {
      const hotelName = route.params.hotelName
      crumbs.push({ path: `/hotel/${hotelName}/rooms`, label: '酒店房间' })
    }
  } else if (path === '/rooms') {
    crumbs.push({ path: '/booking', label: '我要订房' })
    crumbs.push({ path: '/rooms', label: '房间列表' })
  } else if (path === '/order') {
    crumbs.push({ path: '/order', label: '我的订单' })
  } else if (path === '/review') {
    crumbs.push({ path: '/review', label: '我的评论' })
  } else if (path === '/messages') {
    crumbs.push({ path: '/messages', label: '我的消息' })
  } else if (path === '/profile') {
    crumbs.push({ path: '/profile', label: '个人信息' })
  } else if (path === '/user') {
    crumbs.push({ path: '/user', label: '用户管理' })
  } else if (path === '/admin-hotel') {
    crumbs.push({ path: '/admin-hotel', label: '酒店管理' })
  } else if (path === '/admin-order') {
    crumbs.push({ path: '/admin-order', label: '订单列表' })
  } else if (path === '/admin-review') {
    crumbs.push({ path: '/admin-review', label: '评论管理' })
  } else if (path === '/checkout') {
    crumbs.push({ path: '/checkout', label: '我的退房管理' })
  } else if (path === '/checkout-records') {
    crumbs.push({ path: '/checkout-records', label: '历史订单' })
  }
  
  breadcrumbs.value = crumbs
}

// 监听路由变化，更新面包屑
watch(() => route.path, (newPath) => {
  updateBreadcrumbs(newPath)
}, { immediate: true })

// 跳转到个人信息页面
const goToProfile = () => {
  router.push('/profile')
}

// 退出登录
const handleLogout = () => {
  logout().then((res: any) => {
    const result = res.data
    if (result.code === 200) {
      // 清除用户信息
      userInfoStore.clearUserInfo()
      ElMessage.success('退出登录成功')
      // 跳转到登录页
      router.push('/login')
    }
  }).catch((error) => {
    console.error('退出登录错误:', error)
    // 即使API调用失败，也清除本地用户信息并跳转
    userInfoStore.clearUserInfo()
    router.push('/login')
  })
}

// 组件挂载时更新未读消息数量
onMounted(() => {
  updateUnreadCount()
  
  // 定期更新未读消息数量（每分钟）
  const messageInterval = setInterval(() => {
    if (userInfoStore.userInfo) {
      updateUnreadCount()
    }
  }, 60000)
  
  // 在组件卸载时清除定时器
  onBeforeUnmount(() => {
    clearInterval(messageInterval)
  })
})

// 定义所有可用的导航菜单项
const allMenuItems = [
  { 
    path: '/home', 
    label: '首页', 
    icon: 'House',
    customIcon: '/static/png/iconfont/首页.png',
    roles: ['user', 'hotel_owner', 'admin']
  },
  { 
    path: '/booking', 
    label: '我要订房', 
    icon: 'Suitcase',
    customIcon: '/static/png/iconfont/我要订房.png',
    roles: ['user', 'hotel_owner', 'admin'],
    children: [
      {
        path: '/hotel',
        label: '酒店列表',
        icon: 'Location',
        roles: ['user', 'hotel_owner', 'admin']
      },
      {
        path: '/rooms',
        label: '房间列表',
        icon: 'List',
        roles: ['user', 'hotel_owner', 'admin']
      }
    ]
  },
  { 
    path: '/order', 
    label: '我的订单', 
    icon: 'Document',
    customIcon: '/static/png/iconfont/我的订单.png',
    roles: ['user', 'hotel_owner', 'admin']
  },
  { 
    path: '/review', 
    label: '我的评论', 
    icon: 'ChatLineRound',
    customIcon: '/static/png/iconfont/我的评论.png',
    roles: ['user', 'hotel_owner', 'admin']
  },
  { 
    path: '/messages', 
    label: '我的消息', 
    icon: 'Bell',
    customIcon: '/static/png/iconfont/我的消息.png',
    roles: ['user', 'hotel_owner', 'admin']
  },
  { 
    path: '/checkout', 
    label: '我的退房管理', 
    icon: 'SetUp',
    customIcon: '/static/png/iconfont/我的退房管理.png',
    roles: ['user', 'hotel_owner', 'admin']
  },
  { 
    path: '/profile', 
    label: '个人信息', 
    icon: 'User',
    customIcon: '/static/png/iconfont/个人信息.png',
    roles: ['user', 'hotel_owner', 'admin']
  },
  { 
    path: '/my-hotel', 
    label: '我的酒店', 
    icon: 'Suitcase',
    customIcon: '/static/png/iconfont/我的酒店.png',
    roles: ['hotel_owner'], // 只对酒店商家显示，移除管理员
    children: [
      {
        path: '/my-hotel/detail',
        label: '酒店详情',
        icon: 'InfoFilled',
        roles: ['hotel_owner']
      },
      {
        path: '/my-hotel/rooms',
        label: '房间管理',
        icon: 'House',
        roles: ['hotel_owner']
      },
      {
        path: '/my-hotel/orders',
        label: '订单管理',
        icon: 'Document',
        roles: ['hotel_owner']
      },
      {
        path: '/my-hotel/reviews',
        label: '评价管理',
        icon: 'ChatLineRound',
        roles: ['hotel_owner']
      }
    ]
  },
  { 
    path: '/user', 
    label: '用户管理', 
    icon: 'User',
    customIcon: '/static/png/iconfont/用户管理.png',
    roles: ['admin']
  },
  { 
    path: '/admin-hotel', 
    label: '酒店管理', 
    icon: 'Suitcase',
    customIcon: '/static/png/iconfont/酒店管理.png',
    roles: ['admin']
  },
  { 
    path: '/admin-order', 
    label: '订单列表', 
    icon: 'Document',
    customIcon: '/static/png/iconfont/订单管理.png',
    roles: ['admin']
  },
  { 
    path: '/checkout-records', 
    label: '历史订单', 
    icon: 'Document',
    customIcon: '/static/png/iconfont/历史订单.png',
    roles: ['admin']
  },
  { 
    path: '/admin-review', 
    label: '评论管理', 
    icon: 'ChatLineRound',
    customIcon: '/static/png/iconfont/评论管理.png',
    roles: ['admin']
  }
]

// 根据用户角色过滤菜单项
const menuList = computed(() => {
  if (!userInfoStore.userInfo) return []
  
  const isAdmin = userInfoStore.isAdmin()
  const isHotelOwner = userInfoStore.isHotelOwner()
  
  return allMenuItems.filter(item => {
    // 检查菜单项是否适用于当前用户角色
    return item.roles.some(role => {
      if (role === 'admin' && isAdmin) return true
      if (role === 'hotel_owner' && (isHotelOwner || isAdmin)) return true
      if (role === 'user') return true
      return false
    })
  })
})
</script>

<style scoped>
/* 整体布局 */
.layout-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  overflow: hidden;
}

/* 顶部导航栏 */
.header {
  height: 60px;
  width: 100%;
  background-color: #8d6748;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  box-sizing: border-box;
}

.header-left {
  display: flex;
  align-items: center;
}

.logo {
  display: flex;
  align-items: center;
}

.logo-img {
  height: 40px;
  margin-right: 10px;
  object-fit: contain;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  color: #fff;
}

.header-right {
  display: flex;
  align-items: center;
}

/* 消息图标样式 */
.message-icon {
  margin-right: 20px;
  cursor: pointer;
  position: relative;
}

.message-bell {
  font-size: 20px;
  color: #fff;
}

.message-badge :deep(.el-badge__content) {
  background-color: #f56c6c;
}

.username {
  color: #fff;
  margin-right: 15px;
  font-size: 14px;
}

.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid rgba(255, 255, 255, 0.5);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 消息抽屉样式 */
.message-drawer-content {
  padding: 10px;
}

.no-messages {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.loading-messages {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.message-list {
  display: flex;
  flex-direction: column;
}

.message-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
}

.message-item:hover {
  background-color: #f9f6f2;
}

.message-item.unread {
  background-color: #f0f9eb;
  border-left: 3px solid #67c23a;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.message-title {
  font-weight: bold;
  color: #303133;
}

.message-time {
  font-size: 12px;
  color: #909399;
}

.message-content {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 主体内容区域 */
.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 侧边栏 */
.sidebar {
  width: 200px;
  height: 100%;
  background-color: #fff;
  box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
  transition: width 0.3s;
  position: relative;
  z-index: 900;
  display: flex;
  flex-direction: column;
}

.sidebar-collapsed {
  width: 64px;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 200px;
  flex: 1;
  border-right: none;
}

.el-menu-vertical.el-menu--collapse {
  width: 64px;
  flex: 1;
  border-right: none;
}

.collapse-btn {
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  color: #8d6748;
  background-color: #f9f6f2;
  border-bottom: 1px solid #eee;
}

.collapse-btn:hover {
  background-color: #f0e6da;
}

/* 菜单图标 */
.menu-icon-wrapper {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
}

.menu-custom-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: 0;
  background-color: #f9f6f2;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
}

.breadcrumb-container {
  width: 100%;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 0;
  margin-bottom: 20px;
}

.global-breadcrumb {
  padding: 15px 20px;
  font-size: 14px;
}

.router-view-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin: 0 20px 20px 20px;
  flex: 1;
  min-height: calc(100% - 100px);
}

/* 自定义 Element Plus 样式 */
:deep(.el-menu-item.is-active) {
  background-color: #f0e6da !important;
  color: #6e4f32 !important;
  border-left: 4px solid #8d6748;
}

:deep(.el-menu-item:hover) {
  background-color: #f9f6f2 !important;
}

:deep(.el-sub-menu__title:hover) {
  background-color: #f9f6f2 !important;
}

:deep(.el-menu--collapse .el-sub-menu__title) {
  padding: 0 !important;
  text-align: center;
  height: 56px;
  line-height: 56px;
}

:deep(.el-menu--collapse .el-menu-item) {
  padding: 0 !important;
  text-align: center;
}

:deep(.el-menu--collapse .el-menu-item .el-icon),
:deep(.el-menu--collapse .el-sub-menu__title .el-icon) {
  margin: 0 auto;
  width: 24px;
  font-size: 18px;
}

:deep(.el-menu--collapse) {
  width: 64px;
}

:deep(.el-menu--collapse .el-sub-menu) {
  position: relative;
}

:deep(.el-menu--collapse .el-sub-menu .el-icon) {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

:deep(.el-menu--collapse .menu-icon-wrapper) {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  margin: 0;
}

/* 滚动条样式 */
.content::-webkit-scrollbar {
  width: 6px;
  background-color: #f9f6f2;
}

.content::-webkit-scrollbar-thumb {
  background-color: #bfa084;
  border-radius: 3px;
}

.content::-webkit-scrollbar-thumb:hover {
  background-color: #8d6748;
}
</style>
